package com.example.librarymanagementproject2.task;

import com.example.librarymanagementproject2.converter.UserConverter;
import com.example.librarymanagementproject2.mapper.UserMapper;
import com.example.librarymanagementproject2.model.document.UserDocument;
import com.example.librarymanagementproject2.model.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @ClassName UserDataSyncTask
 * @Description 用户数据同步任务
 * @Author Kx
 * @Date 2025/10/23 15:28
 * @Version 1.0
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class UserDataSyncTask {

    private final UserMapper userMapper;
    private final UserConverter userConverter;
    private final ElasticsearchOperations elasticsearchOperations;

    /**
     * @author: kx
     * @date: 2025/10/23 15:30
     * @description: 定时任务，每天凌晨2点同步用户数据到Elasticsearch
    */
    @Scheduled(cron = "0 0 2 * * ?")
    public void syncUserToEs() {
        // 获取所有用户信息
        List<User> users = userMapper.getAllUsers();

        for (User user : users) {
            // 根据id获取用户文档信息
            UserDocument userDocument = elasticsearchOperations.get(user.getId().toString(), UserDocument.class);

            if (userDocument == null) {
                // 如果用户文档信息不存在，则添加用户文档信息
                user.setCreateTime(LocalDateTime.now());
                user.setUpdateTime(null);
                user.setCancelTime(null);
                // 把用户信息转换为用户文档信息
                UserDocument userDocument1 = userConverter.toUserDocument(user);
                // 添加用户文档信息
                elasticsearchOperations.save(userDocument1);
            }
        }
    }
}
